package com.hsd.controller;
import com.hsd.util.JsonConversion;
import com.hsd.model.*;
import com.hsd.service.DeviceInforService;
import com.hsd.service.DeviceService;
import com.hsd.service.FenceService;
import com.hsd.service.MemberService;
import com.hsd.util.AjaxJson;
import org.omg.Messaging.SYNC_WITH_TRANSPORT;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.*;

//import com.hsd.service.DeviceInforService;
//import com.hsd.service.MemberService;

@Controller
@RequestMapping("/monitor")
public class MonitorCpntroller {
    /**
     * 到监控页面
     */
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private FenceService fenceService;
    @Autowired
    private  MemberService memberService;
    @Autowired
    private DeviceInforService deviceInforService;
    //////////////////////////////////////////////////////////////////////////////
    //名称：页面无参数跳转
    //功能:页面跳转
    //备注:None
    //////////////////////////////////////////////////////////////////////////////
    @RequestMapping(value ="device")
    public String list(){
        return "mapmodel/moniter";
    }

    @RequestMapping(value ="fence")
    public String list2(){
        return "mapmodel/personfence";
    }

    @RequestMapping(value ="totrack")
    public String toHistorytrack(HttpServletRequest request, Model model){
        String p=request.getParameter("deviceId");
        try {
            int id = Integer.parseInt(p);
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date etime = new Date();
            String stime="2009-06-01 00:00:00";
            String etim = df.format(etime);
            System.out.println("id=="+id);
            System.out.println("Etime:"+etime);
            System.out.println("Stime:"+stime);
            List<RDeviceInfor>historylist= deviceInforService.getHistoryInforByDeviceId(id, stime, etim);


            List<Object> list=new ArrayList<Object>();

            for(RDeviceInfor obj :historylist)
            {
                Map<String,Object> map = new HashMap<String, Object>();
                String temp=df.format(obj.getUploadTime());
                List<Object> a=new ArrayList<Object>();
                //a.add(obj.getDeviceinforId());
                a.add(obj.getLatLatitude());
                a.add(obj.getLngLongitude());
                //a.add(temp);
                list.add(a);
//                map.put("inforid",obj.getDeviceinforId());
//                map.put("lat",obj.getLatLatitude());
//                map.put("lng",obj.getLngLongitude());
//                map.put("time",temp);
//                list.add(map);
            }
            model.addAttribute("list",list);
            model.addAttribute("id",id);
           // model.addAttribute("list2",timelist);
        }catch (Exception e)
        {
            model.addAttribute("error",e.getMessage());
        }
        model.addAttribute("deviceId",p);
       return "mapmodel/historytrack";
    }

    //进入编辑页面
    @RequestMapping("/edit")    //进入编辑框
    public ModelAndView tobian(){
        ModelAndView mav = new ModelAndView("mapmodel/editfence");
        return mav;
    }
    //////////////////////////////////////////////////////////////////////////////
    //名称：历史轨迹
    //功能:获取历史轨迹数据
    //备注:None
    //////////////////////////////////////////////////////////////////////////////
    @RequestMapping(value ="gettrack")
    @ResponseBody
    public AjaxJson gettrack(HttpSession session,HttpServletRequest request){
        AjaxJson j=new AjaxJson();
        if(!checkUserLogin(session))
        {
            j.setSuccess(false);
            j.setMsg("未登录！请先登录！");
            return j;
        }
        try {
            int id = Integer.parseInt(request.getParameter("device_id"));
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date etime = new Date();
            String stime="2009-06-01 00:00:00";
            String etim = df.format(etime);
            List<RDeviceInfor>historylist= deviceInforService.getHistoryInforByDeviceId(id, stime, etim);
            j.put("id",id);
            j.put("list",historylist);
            j.setSuccess(true);
        }catch (Exception e)
        {
            j.setSuccess(false);
            j.setMsg(e.getMessage());
        }
        return j;
    }
    @RequestMapping(value ="gettrack2")
    @ResponseBody
    public AjaxJson gettrack2(HttpSession session,HttpServletRequest request){
        AjaxJson j=new AjaxJson();
        if(!checkUserLogin(session))
        {
            j.setSuccess(false);
            j.setMsg("未登录！请先登录！");
            return j;
        }
        try {
            int id = Integer.parseInt(request.getParameter("id"));
            String stime = (request.getParameter("stime"));
            String etime = (request.getParameter("etime"));
            List<RDeviceInfor>historylist= deviceInforService.getHistoryInforByDeviceId(id, stime, etime);
            j.put("list",historylist);
            j.setSuccess(true);
        }catch (Exception e)
        {
            j.setSuccess(false);
            j.setMsg(e.getMessage());
        }
        return j;
    }
    //////////////////////////////////////////////////////////////////////////////
    //名称：检查登录
    //功能:检查用户是否登录
    //备注:None
    //////////////////////////////////////////////////////////////////////////////
    public boolean checkUserLogin(HttpSession session){
        RUser user = (RUser) session.getAttribute("user");

        if(user==null) {
            return false;
        }
        return true;
    }

    //////////////////////////////////////////////////////////////////////////////
    //名称：电子栅栏部分
    //功能:电子栅栏的增删改查
    //备注:None
    //////////////////////////////////////////////////////////////////////////////
    @RequestMapping(value ="/addfence")
    @ResponseBody
    public AjaxJson addFence(HttpSession session, HttpServletRequest request) {

        AjaxJson j = new AjaxJson();
        if(!checkUserLogin(session))
        {
            j.setSuccess(false);
            j.setMsg("未登录！请先登录！");
            return j;
        }

        try{
            //({"":,"ByDevice":,"ByMember":,"X":,"Y":,"Radius":,});
            String devi=request.getParameter("ByDevice");
            //System.out.println(devi);
            int ByDevice=Integer.parseInt( devi);
           // System.out.println(ByDevice);
            int ByMember;
            String member=request.getParameter("ByMember");
            //System.out.println(member);
            if(member==null)
            {
                RDevice d=deviceService.search(ByDevice);
                ByMember=d.getMemberId();
            }
            else {
                ByMember = Integer.parseInt(member);
            }
            Double lat=Double.parseDouble(request.getParameter("X"));
           // System.out.println(lat);
            Double lng=Double.parseDouble(request.getParameter("Y"));
           // System.out.println(lng);
            Double Radius=Double.parseDouble(request.getParameter("Radius"));
            //System.out.println(Radius);
            Date t=new Date();

            RFence rFence=new RFence();
            rFence.setDeviceId(ByDevice);

            rFence.setMemberId(ByMember);
            rFence.setRadius(Radius);
            rFence.setFenceTime(t);
            rFence.setLngLongitude(lng);

            rFence.setLatLatitude(lat);
            //System.out.println(rFence);
           // System.out.println(rFence.getRadius());
            int flag=fenceService.InsertFence(rFence);

           // System.out.println(flag);
            if(flag==1)
            {
                j.setSuccess(true);
                j.setMsg("成功插入");
            }
            else{
                System.out.println("插入失败,插入返回值不为1");
                j.setSuccess(false);
                j.setMsg("插入失败,插入返回值不为1");
            }
        }
        catch (Exception e)
        {
            System.out.println(e.getMessage());
            j.setSuccess(false);
            j.setMsg(e.getMessage());
        }
        return j;
    }

    @RequestMapping(value ="/subfence")
    @ResponseBody
    public AjaxJson subFence(HttpSession session, HttpServletRequest request){
        AjaxJson j = new AjaxJson();

        if(!checkUserLogin(session))
        {
            j.setSuccess(false);
            j.setMsg("未登录！请先登录！");
            return j;
        }
        try{
            //({"FenceId":});
            int FenceId=Integer.parseInt(request.getParameter("FenceId"));
            int flag=fenceService.SubFence(FenceId);
            if(flag==1)
            {
                j.setSuccess(true);
                j.setMsg("成功删除");
            }
            else{
                j.setSuccess(false);
                j.setMsg("删除失败,插入返回值不为1");
            }
        }
        catch (Exception e)
        {
            j.setSuccess(false);
            j.setMsg(e.getMessage());
        }
        return j;
    }

    @RequestMapping(value ="/changefence")
    @ResponseBody
    public AjaxJson changeFence(HttpSession session, HttpServletRequest request){
        AjaxJson j = new AjaxJson();

        if(!checkUserLogin(session))
        {
            j.setSuccess(false);
            j.setMsg("未登录！请先登录！");
            return j;
        }
        try{
            //({"FenceId":,"ByDevice":,"ByMember":,"X":,"Y":,"Radius":,});
            int FenceId=Integer.parseInt(request.getParameter("FenceId"));
            int ByDevice=Integer.parseInt( request.getParameter("ByDevice"));
            int ByMember=Integer.parseInt( request.getParameter("ByMember"));
            Double lat=Double.parseDouble(request.getParameter("X"));
            Double lng=Double.parseDouble(request.getParameter("Y"));
            Double Radius=Double.parseDouble(request.getParameter("Radius"));
            RFence rFence=new RFence();
            rFence.setFenceId(FenceId);

            rFence.setDeviceId(ByDevice);
            rFence.setMemberId(ByMember);
            rFence.setLatLatitude(lat);
            rFence.setLngLongitude(lng);
            rFence.setRadius(Radius);
            int flag=fenceService.ChangeFence(rFence);
            if(flag==1)
            {
                j.setSuccess(true);
                j.setMsg("成功更新");
            }
            else{
                j.setSuccess(false);
                j.setMsg("更新失败,sql返回值不为1");
            }
        }
        catch (Exception e)
        {
            j.setSuccess(false);
            j.setMsg(e.getMessage());
        }
        return j;
    }

    @RequestMapping(value ="/searchfence")
    @ResponseBody
    public AjaxJson searchFence(HttpSession session, HttpServletRequest request){
        AjaxJson j = new AjaxJson();
        if(!checkUserLogin(session))
        {
            j.setSuccess(false);
            j.setMsg("未登录！请先登录！");
            return j;
        }
        try{
            //({"FenceId",});
            int FenceId=Integer.parseInt(request.getParameter("FenceId"));
            RFence rFence=fenceService.SelectFence(FenceId);
            if(rFence!=null)
            {
                j.put("RFence",rFence);
                j.setSuccess(true);
                j.setMsg("查询成功");
            }
            else{
                j.setSuccess(false);
                j.setMsg("查询失败,sql返回值为null");
            }
        }
        catch (Exception e)
        {
            j.setSuccess(false);
            j.setMsg(e.getMessage());
        }
        return j;
    }

    //备用
    @RequestMapping(value ="/getallfence2")
    @ResponseBody
    public AjaxJson getAllFence(HttpSession session){
        AjaxJson j = new AjaxJson();
        if(!checkUserLogin(session))
        {
            j.setSuccess(false);
            j.setMsg("未登录！请先登录！");
            return j;
        }
        List<RFence> ALLlist=fenceService.GetAllList();
        j.put("list",ALLlist);
        j.setSuccess(true);
        return j;

    }

    //显示所有公告并分页

    @ResponseBody
    @RequestMapping(value="/getallfence",produces="application/json; charset=UTF-8")
    public String findListByPage(
            @RequestParam(value="page")int page,
            @RequestParam(value="limit")int limit,
            Model model,
            HttpServletRequest request)
    {
        int start = (page-1)*limit + 1;
        int end = page*limit;
        int count = fenceService.getfencecount();
        List<RFence> userList = fenceService.findListByPage(start,end);
        List<Object> list_temp= new ArrayList<Object>();
        for(RFence rfence:userList)
        {
            Map<String,Object> te=rfence.getAll();
            Map<String,Object> tem_name= memberService.SearchMemberandDeviceNameBydeviceid(rfence.getDeviceId());
            //System.out.println(tem_name);
            te.put("deviceName",tem_name.get("DEVICE_NAME"));
            te.put("memberName",tem_name.get("MEMBER_NAME"));
            list_temp.add(te);
        }
        Map<Object, Object> map = new HashMap<Object, Object>();
        if (userList!=null && userList.size()>0) {
            map.put("code", 0);
            map.put("msg", "success");
            map.put("count", count);
            map.put("data", list_temp);
        }else {
            map.put("code", -1);
            map.put("msg", "无数据");
            map.put("data", "");
        }

        return  JsonConversion.writeMapJSON(map);
    }

    //////////////////////////////////////////////////////////////////////////////
    //名称：设备部分
    //功能:设备的增删改查
    //备注:None
    //////////////////////////////////////////////////////////////////////////////
    @RequestMapping(value ="/adddevice")
    @ResponseBody
    public AjaxJson addDevice(HttpSession session,RDevice device) {
        AjaxJson j=new AjaxJson();
        if(!checkUserLogin(session))
        {
            j.setSuccess(false);
            j.setMsg("未登录！请先登录！");
            return j;
        }
        int ans=deviceService.add(device);
        if(ans!=1)
        {
            j.setSuccess(false);
            j.setMsg("数据库插入失败");
            return j;
        }
        j.setSuccess(true);
        return j;
    }

    @RequestMapping(value ="/deletedevice")
    @ResponseBody
    public AjaxJson deleteDevice(HttpSession session,RDevice device) {
        AjaxJson j=new AjaxJson();
        if(!checkUserLogin(session))
        {
            j.setSuccess(false);
            j.setMsg("未登录！请先登录！");
            return j;
        }
        int ans=deviceService.delete(device.getDeviceId());
        if(ans!=1){
            j.setSuccess(false);
            j.setMsg("数据库删除失败");
            return j;
        }
        j.setSuccess(true);
        return j;
    }

    @RequestMapping(value ="/changedevice")
    @ResponseBody
    public AjaxJson changeDevice(HttpSession session,RDevice device) {
        AjaxJson j=new AjaxJson();
        if(!checkUserLogin(session))
        {
            j.setSuccess(false);
            j.setMsg("请先登录");
            return j;
        }
        int ans=deviceService.ChangeDevice(device);
        if(ans!=1)
        {
            j.setSuccess(false);
            j.setMsg("数据库更新失败");
            return j;
        }
        j.setSuccess(true);
        return j;
    }

    @RequestMapping(value ="/searchdevice")
    @ResponseBody
    public AjaxJson searchDevice(HttpSession session,RDevice device) {
        AjaxJson j=new AjaxJson();
        if(!checkUserLogin(session))
        {
            j.setSuccess(false);
            j.setMsg("未登录！请先登录！");
            return j;
        }
        RDevice deviceans=deviceService.search(device.getDeviceId());
        if(deviceans==null){
            j.setSuccess(false);
            j.setMsg("数据库查询失败");
            return j;
        }
        j.setSuccess(true);
        return j;
    }

    @RequestMapping(value ="/getalldevice")
    @ResponseBody
    public AjaxJson getalldevice(HttpSession session) {
        AjaxJson j=new AjaxJson();
        if(!checkUserLogin(session))
        {
            j.setSuccess(false);
            j.setMsg("未登录！请先登录！");
            return j;
        }
        List<RDevice> deviceans=deviceService.GetDeviceList();
        if(deviceans==null){
            j.setSuccess(false);
            j.setMsg("数据库查询失败");
            return j;
        }
        j.setSuccess(true);
        j.put("list",deviceans);
        return j;
    }
    //////////////////////////////////////////////////////////////////////////////
    //名称：查询设备历史时间
    //功能:设备历史时间查询
    //备注:None
    //////////////////////////////////////////////////////////////////////////////
    @RequestMapping(value ="/searchhistorydevice")
    @ResponseBody
    public AjaxJson searchhistorydevice(HttpSession session,HttpServletRequest request){
        AjaxJson j = new AjaxJson();
        if(!checkUserLogin(session))
        {
            j.setSuccess(false);
            j.setMsg("未登录！请先登录！");
            return j;
        }
        String str="2006-12-12 06:08:54";
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            String date = request.getParameter("STime");
            String date2 = request.getParameter("ETime");
            int deviceid=Integer.parseInt(request.getParameter("DEVICE_ID"));
            List<RDeviceInfor> listall=deviceInforService.getHistoryInforByDeviceId(deviceid,date,date2);
            j.put("list",listall);
            j.setSuccess(true);
        }
        catch (Exception e){
            j.setSuccess(false);
            j.setMsg(e.getMessage()+"未接收到值！或日期无法转换");
            return j;
        }

       return j;
    }
    //////////////////////////////////////////////////////////////////////////////
    //名称：查询数据表分组
    //功能:分组的增删改查
    //备注:None
    //////////////////////////////////////////////////////////////////////////////
    @RequestMapping(value ="/loadtodata")
    @ResponseBody
    public AjaxJson getData(HttpSession session){

        AjaxJson j = new AjaxJson();

        RUser user = (RUser)session.getAttribute("user");

        //List<RDevice> Allinforlist =  deviceService.MultiTableq();
        List<RMember> Allinforlist =  memberService.MultiTableList();

        //        /*分组*/
        Map<String,List<Object>> map = new HashMap<String, List<Object>>();
        Map<String,List<Object>> map_on_off_null = new HashMap<String, List<Object>>();
        map_on_off_null.put("unused",null);
        for(RMember obj : Allinforlist){
            if(obj.getDevice().get(0).getInfor().get(0).getDeviceStatus()!=null) {
                if (map_on_off_null.containsKey(obj.getDevice().get(0).getInfor().get(0).getDeviceStatus())) {
                    Map<String, Object> temp = new HashMap<>();
                    temp.put("body", obj);
                    temp.put("name", obj.getMemberName());
                    map_on_off_null.get(obj.getDevice().get(0).getInfor().get(0).getDeviceStatus()).add(temp);
                } else {
                    Map<String, Object> temp = new HashMap<>();
                    temp.put("body", obj);
                    temp.put("name", obj.getMemberName());
                    List<Object> tmpList = new ArrayList<Object>();
                    tmpList.add(temp);
                    map_on_off_null.put(obj.getDevice().get(0).getInfor().get(0).getDeviceStatus(), tmpList);
                }
            }
            else
            {
                Map<String, Object> temp = new HashMap<>();
                temp.put("body", obj);
                temp.put("name", obj.getMemberName());
                List<Object> tmpList = new ArrayList<Object>();
                tmpList.add(temp);
                map_on_off_null.put("未启用", tmpList);
            }
            if(map.containsKey(obj.getMemberGroup())){//map中存在此id，将数据存放当前key的map中
                Map <String,Object> temp= new HashMap<>();
                temp.put("body",obj);
                temp.put("name",obj.getMemberName());
                map.get(obj.getMemberGroup()).add(temp);
            }else{//map中不存在，新建key，用来存放数据
                Map <String,Object> temp= new HashMap<>();
                temp.put("body",obj);
                temp.put("name",obj.getMemberName());
                List<Object> tmpList = new ArrayList<Object>();
                tmpList.add(temp);
                map.put(obj.getMemberGroup(),tmpList);
            }
        }
        int a=1;

        List<Object> group_list_temp=new ArrayList<Object>();
        for(Map.Entry<String, List<Object>> entry : map.entrySet()){
            Map<String, Object> jtemp= new HashMap<String, Object>();
            jtemp.put("name",entry.getKey());
            jtemp.put("children",entry.getValue());

            group_list_temp.add(jtemp);
        }


        if (user != null) {

            j.setSuccess(true);
            j.setMsg("成功！");
            j.put("list",Allinforlist);
            j.put("grouplist",map);
            j.put("group",group_list_temp);
            j.put("grouplist2",map_on_off_null);


        } else {
            j.setSuccess(false);
            j.setMsg("未登录！");
        }

        return j;
//        List<RDevice> list = deviceService.GetDeviceList();
//        List<RMember> memberlist = memberService.GetALLList();
//        List<RDeviceInfor> deviceInforlist=deviceInforService.GetdeviceinforALLList();
        // JSONArray jsonArray = JSONArray.fromObject(list);
//        Object[] objs = list.toArray();

//
//
//
//
//
//
//        for(int i = 0;i < list.size();i++){
//            System.out.println("it's "+i);
//            System.out.println(deviceInforlist.get(i));
//        }
//

    }

    @RequestMapping(value ="/searchmember")
    @ResponseBody
    public AjaxJson searchDeviceByMemberName(HttpSession session, HttpServletRequest request){
        AjaxJson j = new AjaxJson();
        if(!checkUserLogin(session))
        {
            j.setSuccess(false);
            j.setMsg("未登录！请先登录！");
            return j;
        }
        String membername=request.getParameter("membername");
        if(membername==null) {
            j.setSuccess(false);
            j.setMsg("未接收到值！");
            return j;
        }
        List<RDevice> Allinforlist = deviceService.MultiTableqBymemberName(membername);
        //        /*分组*/
        //Map<String, List<RDevice>> map = new HashMap<String, List<RDevice>>();
        //for(RDevice obj : Allinforlist){
//            if(map.containsKey(obj.getUser().getBygroup())){//map中存在此id，将数据存放当前key的map中
//                map.get(obj.getUser().getBygroup()).add(obj);
//            }else{//map中不存在，新建key，用来存放数据
//                List<RDevice> tmpList = new ArrayList<RDevice>();
//                tmpList.add(obj);
//                map.put(obj.getUser().getBygroup(), tmpList);
//            }
//        }
//        List<Object> group_list_temp=new ArrayList<Object>();
//        for(Map.Entry<String, List<RDevice>> entry : map.entrySet()){
//            Map<String, Object> jtemp= new HashMap<String, Object>();
//            jtemp.put("name",entry.getKey());
//            jtemp.put("children",entry.getValue());
//
//            group_list_temp.add(jtemp);
//            System.out.println("键 key ："+entry.getKey()+" 值value ："+entry.getValue());
//            for(RDevice obj:entry.getValue()){
//                j2.put("children",obj);
//            }
 //       }
        j.put("list",Allinforlist);
        j.setSuccess(true);
        return j;
    }

    @RequestMapping(value ="/changegroup")
    @ResponseBody
    public AjaxJson changeGroupByMemberId(HttpSession session, HttpServletRequest request){
        AjaxJson j = new AjaxJson();
        if(!checkUserLogin(session))
        {
            j.setSuccess(false);
            j.setMsg("未登录！请先登录！");
            return j;
        }
        int memberid=Integer.parseInt(request.getParameter("MemberId"));
        String Group=request.getParameter("ByGroup");
        if(request.getParameter("MemberId")==null||Group==null)
        {
            j.setSuccess(false);
            j.setMsg("未取到值!");
            return j;
        }
        RMember rMember=new RMember();
        rMember.setMemberId(memberid);
        rMember.setMemberGroup(Group);
        int ans=memberService.ChangeMember(rMember);
        if(ans!=1)
        {
            j.setSuccess(false);
            j.setMsg("sql更改出错");
        }
        else
        {
            j.setSuccess(true);
        }
        return j;
    }


}
